package guiCode;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.Random;

import secretary.defineSemester;


import flexibility.sendMail;
import flexibility.userData;
import basic.ClientConsole;
import flexibility.serverIP;
import gui.ManagerGUI;
import gui.TeacherMainMenuGUI;
import gui.loginScreen;
import gui.parentViewScreen;
import gui.secretaryScreen;
import gui.studentScreen;
import com.sun.rowset.CachedRowSetImpl;

public class loginScreenCode {
	
	private checkDataBase busy = new checkDataBase();
	private CachedRowSetImpl crs;
	private CachedRowSetImpl crs2;
	private CachedRowSetImpl crs3;
	private loginScreen ls = new loginScreen();
	private userData updateStudents = new userData();
	private userData updateDB = new userData();
	private defineSemester ds = new defineSemester();
	sendMail email = new sendMail();

	serverIP server = new serverIP();
	ClientConsole startConnection;
	int i = 1;
	userData userInfo = new userData();

	private String userName;
	private String password;

	public loginScreenCode(){
		
		
	}
	private void signIn() throws UnknownHostException {// a is userName, b is password
		userInfo.deleteAll();// reset user info
		userInfo.addData(1);// this is the query code
		userInfo.addData(1);// this is for the select statement
		userInfo.addData(userName);
		userInfo.addData(password);
		userInfo.addData(password);

		//server.getServerConf();
		//startConnection = new ClientConsole(server.host, server.port);// creates
																		// the
																		// client
																		// object
		startConnection.acceptMsg(userInfo);// this submits the query to the
											// server
		crs = startConnection.getResults();// this will get the results from the
											// server
		checkForErrors();// this will check if the result are empty
	}

	/*public void signOut(){
		userInfo.deleteAll();
		userInfo.addData(5);
		userInfo.addData(0);
		userInfo.addData(userName);
		startConnection.acceptMsg(userInfo);
	}*/
	
	public void setUserName(String name) {
		userName = name;
	}

	public void setPassword(String pass) {
		password = pass;
	}

	public void setInfo()  {
		try {
			signIn();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void checkForErrors()  {
		try {
			if (crs.next() == false) {// if the results of the select are empty
				ls.showMessages(
						"The username or password you entered is incorrect.",
						"User information failure",1);
				
			} else {// if the results has user information
				try {
					crs.beforeFirst();// return pointer to the beginning of the
										// results
					logIn();// log in the user to the system
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	private void logIn()  {// this will log in the user to the system
		try {
			crs.next();
			if (crs.getString(5) == "false" || (crs.getString(5) == "true" && crs.getString(6).equals(password.toString())) &&crs.getString(6).equals("0")==false) {
				InetAddress addr = null ;//holds the ip of the client
				try {
					addr = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  //this is for the user's ip address
				
				if(crs.getString(6).equals("0")==false && crs.getString(5).equals("1")){
					userInfo.deleteAll();
					userInfo.addData(6);//just a simple query
					userInfo.addData(3);//code to close previous connection for this user
					userInfo.addData(crs.getString(7));//user's ip of the previous active connection
					startConnection.acceptMsg(userInfo);
					startConnection.getResults();
				}
				
				userInfo.deleteAll();// reset user info
				userInfo.addData(2);// this is the query code
				userInfo.addData(0);// this is for the update statement
				userInfo.addData(1);// changing state to logged in
				userInfo.addData(0);// changing resetCode to defualt
				userInfo.addData(addr.getHostAddress());
				userInfo.addData(crs.getString(1));// this is the userID
				busy.setBusy(true);
				startConnection.acceptMsg(userInfo);
		    	startConnection.getResults();
				busy.setBusy(false);
				System.out.println("welcome " + crs.getString(1));
				
				/*this is an update to several database tables*/
				//update studentsVSclasses table
				//this will read the students from the users table
				updateStudents.deleteAll();
				updateStudents.addData(500);
				updateStudents.addData(1);
				startConnection.acceptMsg(updateStudents);
				crs2 = startConnection.getResults();
				updateStudents.deleteAll();
				while(crs2.next()){
					//this will put student details into updateStudents structure
					updateStudents.addData(crs2.getString(1));
					//updateStudents.addData(crs2.getString(2));
					//updateStudents.addData(crs2.getString(3));
				}
				for(int i =0; i<updateStudents.getLength();i=i+3 ){
					//check if user exists in studentsVSclasses
					updateDB.deleteAll();
					updateDB.addData(180);
					updateDB.addData(1);
					updateDB.addData(updateStudents.getData(i));
					startConnection.acceptMsg(updateDB);
					crs2 = startConnection.getResults();
					if(crs2.next()==false){
						//case the user does not exist - insert user
						updateDB.deleteAll();
						updateDB.addData(241);
						updateDB.addData(0);
						updateDB.addData(updateStudents.getData(i));
						//updateDB.addData(updateStudents.getData(i+1));
						//updateDB.addData(updateStudents.getData(i+2));
						updateDB.addData(ds.identify(0, startConnection, crs));
						startConnection.acceptMsg(updateDB);
						crs2 = startConnection.getResults();
					}
				/*	else{
						//case the user exists - update user
						updateDB.deleteAll();
						updateDB.addData(179);
						updateDB.addData(0);
						updateDB.addData(updateStudents.getData(i));
						updateDB.addData(updateStudents.getData(i+1));
						updateDB.addData(updateStudents.getData(i+2));
						updateDB.addData(updateStudents.getData(i));
						startConnection.acceptMsg(updateDB);
						crs2 = startConnection.getResults();
					}*/
					
					//update the students table
					updateStudents.deleteAll();
					updateStudents.addData(500);
					updateStudents.addData(1);
					startConnection.acceptMsg(updateStudents);
					crs2 = startConnection.getResults();
					updateDB.deleteAll();
					while(crs2.next()){
						updateDB.addData(crs2.getString(1));
					}
					for(i=0; i<updateDB.getLength();i++){
						updateStudents.deleteAll();
						updateStudents.addData(561);
						updateStudents.addData(1);
						updateStudents.addData(updateDB.getData(i));
						startConnection.acceptMsg(updateStudents);
						crs3 = startConnection.getResults();
						if(crs3.next()==false){
							//student should be added to the student table
							updateStudents.deleteAll();
							updateStudents.addData(562);
							updateStudents.addData(1);
							updateStudents.addData(updateDB.getData(i));
							startConnection.acceptMsg(updateStudents);
							crs3 = startConnection.getResults();
							crs3.next();
							updateStudents.deleteAll();
							updateStudents.addData(563);
							updateStudents.addData(0);
							updateStudents.addData(updateDB.getData(i));
							updateStudents.addData(crs3.getString(1));
							updateStudents.addData(crs3.getString(2));
							updateStudents.addData(0);
							updateStudents.addData(0);
							startConnection.acceptMsg(updateStudents);
							crs3 = startConnection.getResults();
							;
							
							
						}
					}
					//update the parents table
					
					//update teachers table
					updateStudents.deleteAll();
					updateStudents.addData(404);
					updateStudents.addData(1);
					startConnection.acceptMsg(updateStudents);
					crs2 = startConnection.getResults();
					updateStudents.deleteAll();
					while(crs2.next()){
						i++;
						updateStudents.addData(crs2.getString(1));
						updateStudents.addData(crs2.getString(2));
						updateStudents.addData(crs2.getString(3));
					}
					for( i = 0; i< updateStudents.getLength(); i=i+3){
						updateDB.deleteAll();
						//check if the teacher already exists
						updateDB.addData(406);
						updateDB.addData(1);
						updateDB.addData(updateStudents.getData(i));
						startConnection.acceptMsg(updateDB);
						crs2 = startConnection.getResults();
						if(crs2.next()==false){
							//teacher will be added to the teachers table
							updateDB.deleteAll();
							updateDB.addData(405);
							updateDB.addData(0);
							updateDB.addData(updateStudents.getData(i));
							updateDB.addData(updateStudents.getData(i+1));
							updateDB.addData(updateStudents.getData(i+2));
							updateDB.addData(0);
							startConnection.acceptMsg(updateDB);
							crs2 = startConnection.getResults();
						}
						
					}
				}
				/*for(i = 241; i< 281; i++){
					updateDB.deleteAll();
					updateDB.addData(485);
					updateDB.addData(0);
					updateDB.addData(i);
					startConnection.acceptMsg(updateDB);
					crs2 = startConnection.getResults();
				}*/
				if (crs.getString(3).equals("2")) {
					secretaryScreenCode secretary = new secretaryScreenCode(startConnection,Integer.parseInt(crs.getString(1)) );
					secretaryScreen scretaryGUI = new secretaryScreen(startConnection);
					scretaryGUI.setConnectionToCode(secretary);
					secretary.setSecretaryGUI(scretaryGUI);
					ls.closeLoginScreen();
				}
				if(crs.getString(3).equals("3")){
					TeacherMainMenuGUI teacher = new TeacherMainMenuGUI(startConnection,Integer.parseInt(crs.getString(1)));
					ls.closeLoginScreen();
				}
				

				if (crs.getString(3).equals("4")) {
					studentScreen student = new studentScreen(startConnection,Integer.parseInt(crs.getString(1)));
					ls.closeLoginScreen();
				}


				/*connect to manager Screen*/
				else if (crs.getString(3).equals("1")) {
					ManagerGUI manager = new ManagerGUI(startConnection,Integer.parseInt(crs.getString(1)));
					ls.closeLoginScreen();
				}
				/*connect to parent Screen*/
				else if (crs.getString(3).equals("5")) {
					 new parentViewScreen(startConnection,Integer.parseInt(crs.getString(1)));
					ls.closeLoginScreen();
				}
				


			}
			if ((crs.getString(5) == "true" && crs.getString(6).equals(password.toString())==false) || (crs.getString(5) == "true" && crs.getString(6).equals("0"))) {
				ls.showMessages(
						"User is already logged  in to the system.\nAccess is denied",
						"Login failure",1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.getErrorCode();
		}
	}
	
	public void recoverType(int type){
		switch(type){
		case 1://user get message that he is already logged in
			Random rand = new Random();//generating code number
			int  code  = rand.nextInt() + 1;
			
			userInfo.deleteAll();
			userInfo.addData(5);//updating user code in database
			userInfo.addData(0);
			userInfo.addData(code);
			userInfo.addData(userName);
			busy.setBusy(true);
			startConnection.acceptMsg(userInfo);
			startConnection.getResults();
			busy.setBusy(false);
			
			passwordRecovery(type);
			break;
		case 2:
			passwordRecovery(type);
			break;
			
		}
	}

	public void passwordRecovery(int type) {//this will handle password recovery for users
		userInfo.deleteAll();// reset user info
		userInfo.addData(6);// this is the query code
		userInfo.addData(1);// this is for the select statement
		userInfo.addData(userName);
		//server.getServerConf();
	//	startConnection = new ClientConsole(server.host, server.port);// creates
																		// the
																		// client
																		// object
		startConnection.acceptMsg(userInfo);// this submits the query to the
		// server
		
		crs = startConnection.getResults();// this will get the results from the
		// server
		try {
			if(crs.next()==false){
				ls.showMessages("The username you entered is incorrect", "User information failure",1);
			}
			else{
			crs.beforeFirst();
			crs.next();
			switch(type){
			case 1:
				email.sendEmail(crs.getString(4), crs.getString(6), 1);
				break;
			case 2:
				email.sendEmail(crs.getString(4), crs.getString(2), 2);
				break;
			}
			
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	

	public void fillServerDetails(){
		//this will read the server configuration
		server.getServerConf();
		ls.setServerDetails(server.host,server.port);
	}
	
	public boolean connectToServer(String host, String port){
		startConnection = new ClientConsole(host,Integer.parseInt(port));// creates
		if(startConnection.getStatus()==false){
			return false;
		}
		return true;
	}

}
